import { nextTick, ref } from 'vue'
import InterviewQuestionsForm from '../InterviewQuestionsForm.vue'
import { notification, message } from 'ant-design-vue'
import { useInterviewQuestionsSearchFormState } from './useInterviewQuestionsSearchFormState'
import { add } from '@/apis/InterviewQuestions'

export function useInterviewQuestionsAdd(entityName: string, searchFunc: () => void) {
  const addModal = ref(false)
  const addLoading = ref(false)
  const addFormRef = ref<null | InstanceType<typeof InterviewQuestionsForm>>()
  const { resetFormState, setFormState } = useInterviewQuestionsSearchFormState()

  function onAdd() {
    addModal.value = true
    nextTick(() => {
      if (!addFormRef.value) return
      //   addFormRef.value?.resetFormStata()
    })
  }

  function onAddCancel() {
    addModal.value = false
    addLoading.value = false
  }

  async function onAddOk(closeModal = true, resetForm = true) {
    const formData = await addFormRef.value?.getFormState()
    if (addLoading.value) return
    if (!formData) return
    if (!formData.title) return
    if (!formData.answer) return
    setFormState(formData)
    addLoading.value = true
    try {
      const res = await add({
        title: formData.title,
        answer: formData.answer,
        classification: formData.classification,
        secondaryClassification: formData.secondaryClassification,
      })
      if (res.data) {
        message.success(`添加${entityName}成功!`)
        searchFunc()
        if (resetForm) {
          const tempClassification = formData.classification
          const tempSecondaryClassification = formData.secondaryClassification
          addFormRef.value?.resetFormStata()
          resetFormState()
          addFormRef.value?.setFormStata({
            classification: tempClassification,
            secondaryClassification: tempSecondaryClassification,
          })
          formData.classification = tempClassification
          formData.secondaryClassification = tempSecondaryClassification
        }
        if (closeModal) onAddCancel()
        addLoading.value = false
        return
      } else {
        notification.error({ message: `添加${entityName}失败!` })
      }
    } catch (error) {
      notification.error({
        message: `添加${entityName}失败!`,
      })
    }
    addLoading.value = false
  }

  return {
    addModal,
    addLoading,
    addFormRef,
    onAdd,
    onAddOk,
    onAddCancel,
  }
}
